package com.humbleyuan.blogfront.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.humbleyuan.blogfront.constant.CommentConstant;
import com.humbleyuan.blogfront.entity.comment.CommentMain;
import com.humbleyuan.blogfront.entity.comment.CommentReplay;
import com.humbleyuan.blogfront.entity.user.VisitUser;
import com.humbleyuan.blogfront.mapper.MainCommentMapper;
import com.humbleyuan.blogfront.mapper.ReplayCommentMapper;
import com.humbleyuan.blogfront.mapper.VisitUserMapper;
import com.humbleyuan.blogfront.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: HumbleYuan
 * @description: 评论业务层实现类
 * @Date: 2019/8/9
 * @Time: 13:57
 * @Version: 1.0
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    MainCommentMapper mainCommentMapper;

    @Autowired
    VisitUserMapper visitUserMapper;

    @Autowired
    ReplayCommentMapper replayCommentMapper;

    /**
     * 获取所有留言板评论
     *
     * @return list<CommentMain>
     */
    @Override
    public List<CommentMain> getRootCommentListsWithAllReplays() {

        //获取所有评论信息
        List<CommentMain> commentMainList =
                mainCommentMapper.getRootCommentListsWithAllReplays();

        /*
            添加评论者对象VisitUser,也可以在上一个查询进行多个join查询，但影响查询效率
            其实我这里只是关联两张表查询，不算多可直接查
            超过三张就需要在service层进行合并操作了
         */
        for (CommentMain cm : commentMainList
        ) {
            VisitUser mv = visitUserMapper.getVisitUserById(cm.getVUserId());

            // 游客发布
            if (mv == null) {
                mv = new VisitUser();
                mv.setVUserId(-1);
                mv.setVUserName("游客");
            }

            cm.setVisitUser(mv);

            // 设置默认头像
            if (cm.getVisitUser().getVImage() == null)
                cm.getVisitUser().setVImage(CommentConstant.defaultHeadImg);

            //为回复设置评论的用户
            if (cm.getCommentReplayList().size() != 0) {
                for (CommentReplay cr : cm.getCommentReplayList()
                ) {
                    VisitUser v = visitUserMapper.getVisitUserById(cr.getVUserId());

                    if(cr.getVUserId() == null || v == null) {  // 查不到指定用户默认为游客
                        v = new VisitUser();

                        v.setVUserId(-1);
                        v.setVUserName("游客");
                        v.setVImage(CommentConstant.defaultHeadImg);  // 设置游客默认头像
                    }

                    cr.setVisitUserUsername(v.getVUserName());
                    cr.setVisitUserImage(v.getVImage());

                    // 设置父评论的用户名
                    cr.setParentUsername(visitUserMapper.
                            getUsernameById(cr.getParentId()));
                }
            }
        }

        return commentMainList;
    }

    /**
     * 获取所有评论中有多少不同用户参与
     *
     * @return int
     */
    @Override
    public int getDifCommentUserNum() {
        return mainCommentMapper.getDifCommentUserNum();
    }

    /**
     * 获取所有回复的条数
     *
     * @return int
     */
    @Override
    public int getReplayCommentNum() {
        return replayCommentMapper.getAllReplaysNum();
    }

    /**
     * 提交主评论
     *
     * @param jsonobject
     * @return int(数据库更新结果)
     */
    @Override
    public int commitMainComment(JSONObject mainComment) {
        /**
         * 数据格式：
         * {"comment":{"ip":"223.104.212.111","area":"CHINA",
         * "mContent":"你好啊","mCommitTime":"2019-7-16 13:34:19",
         * "mUsername":"12","mImageUrl":"22"}}
         */
        CommentMain cm = new CommentMain();     //评论对象
        String commitType = mainComment.getString("type");  //提交的用户类型

        if (("new").equals(commitType)) {
            //新用户需要新增
            addNewUser(mainComment);

            //设置新用户id
            cm.setVUserId(visitUserMapper.
                    getUserIdByUsername(mainComment.getString("mUsername")));
        } else {//老用户||游客

            //老用户需要添加相应userId,type="游客"则不需要
            if (("old").equals(commitType)) {

                cm.setVUserId(visitUserMapper.
                        getUserIdByUsername(mainComment.getString("mUsername")));
            }

        }

        /**
         *ip还是决定放入用户表，每次提交时查询用户表：
         * 1.验证用户是否存在，暂时根据用户名，
         *      若用户名一样，则不新增用户；若不一样则新增用户
         * 2.并实时修改ipip不放入评论表
         */

        //赋需要提交的主评论对象
        cm.setMContent(mainComment.getString("mContent"));
        cm.setMCommitTime(mainComment.getDate("mCommitTime"));

        //此处都是针对的留言板，针对文章的评论待定,设定mCommentType=2
        cm.setMCommentType(2);

        return mainCommentMapper.commitMainComment(cm);
    }

    /**
     * 提交回复类型评论
     *
     * @return int提交结果
     * @Param JSONObject replyComment
     */
    @Override
    public int commitReplyComment(JSONObject replyComment) {
        /**
         * 数据格式：
         * "comment":{ rContent:"",mUsername:"",mPwd:"",
         *     mImageUrl:"",rCommentType:"",mCommentId:"",
         *     parentId:"",rCommitTime:"",ip:"",
         *     area:"",newUserPwd:""(新用户设置的密码)
         * }
         */
        CommentReplay cr = new CommentReplay();

        String commitType = replyComment.getString("type");  //提交的用户类型

        /**
         * 根据type对应用户类型执行相应操作
         */
        if (("new").equals(commitType)) {

            //新用户需要新增
            this.addNewUser(replyComment);

            //设置新用户id
            cr.setVUserId(visitUserMapper.
                    getUserIdByUsername(replyComment.getString("mUsername")));
        } else {//老用户||游客

            //老用户需要添加相应userId,type="游客"则不需要
            if (("old").equals(commitType)) {

                cr.setVUserId(visitUserMapper.
                        getUserIdByUsername(replyComment.getString("mUsername")));
            }
        }

        //赋需要提交的回复评论对象
        cr.setRContent(replyComment.getString("rContent"));
        cr.setRCommitTime(replyComment.getDate("rCommitTime"));
        cr.setMCommentId(replyComment.getInteger("mCommentId"));
        cr.setParentId(replyComment.getInteger("parentId"));

        /**
         * 若直接父评论和根评论一样，说明回复的对象就是根评论
         * 1.回复的是主评论
         * 2.回复的是回复评论
         */
        cr.setRCommentType(replyComment.getInteger("rCommentType"));

        return replayCommentMapper.commitReplyComment(cr);
    }

    /**
     * 新增用户
     *
     * @Param JSONObject
     */
    @Override
    public void addNewUser(JSONObject comment) {

        VisitUser visitUser = new VisitUser();

        visitUser.setVUserName(comment.getString("mUsername"));
        visitUser.setVIP(comment.getString("ip"));
        visitUser.setVAddress(comment.getString("area"));
        visitUser.setVImage(comment.getString("mImageUrl"));
        visitUser.setVPwd(comment.getString("newUserPwd"));

        //新增用户
        visitUserMapper.addVisitUser(visitUser);
    }
}
